package db

import (
	"fmt"
	"time"

	"sieve_admin_server_userpass/pkg/app"
	"sieve_admin_server_userpass/pkg/config"
	"sieve_admin_server_userpass/pkg/mysql"
	"sieve_admin_server_userpass/pkg/redis"
)

var (
	dbPwd      = "PtkBn]adE-"
	fDBAddr    = config.String("db.mysql.addr", "127.0.0.1:3306", "mysql addr")
	fDBName    = config.String("db.mysql.name", "im2", "mysql db name")
	fDBUser    = config.String("db.mysql.user", "im", "mysql db user")
	fDBPwd     = config.String("db.mysql.pwd", "", "mysql db password")
	redisPwd   = ""
	fRedisAddr = config.String("db.redis.addr", "127.0.0.1:6379", "redis addr")
	fRedisPwd  = config.String("db.redis.pwd", "", "redis password")

	LoaderPeriod = time.Duration(*config.Int("im3.dbloader.period", 10, "")) * time.Second

	_inits = []func(){}
	_mysql *mysql.DB
	_redis *redis.Client
)

func init() {
	app.OnStart(func() {
		if *fDBPwd != "" {
			dbPwd = *fDBPwd
		}
		if *fRedisPwd != "" {
			redisPwd = *fRedisPwd
		}
		_mysql, _ = mysql.Open(*fDBAddr, *fDBUser, dbPwd, *fDBName)
		_redis = redis.Connect(&redis.Server{Addr: *fRedisAddr, Pwd: redisPwd})
		for _, fn := range _inits {
			fn()
		}
	})
}

func OnConnected(fn func()) {
	_inits = append(_inits, fn)
}

func Mysql() *mysql.DB     { return _mysql }
func Redis() *redis.Client { return _redis }

func UserKey(uid int, key string) string {
	return fmt.Sprintf("User/%d/%s", uid, key)
}
